package middleware

import (
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"github.com/pkg/errors"
	"runtime"
	"strings"
	"time"
	"trpg-common/dto"
	"trpg-common/logger"
	"trpg-common/response"
	"trpg-common/utils/redis_util"
)

func Cors() gin.HandlerFunc {
	return cors.New(cors.Config{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"*"},
		ExposeHeaders:    []string{"ContentUrl-Length", "Authorization", "ContentUrl-Type"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	})
}

func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			err := recover()
			if err != nil {
				if runtimeErr, ok := err.(runtime.Error); ok {
					logger.Logger.Errorf("%+v", errors.Wrap(runtimeErr, "error in runtime"))
					c.JSON(500, gin.H{
						"message": runtimeErr.Error(),
					})
					c.Abort()
					return
				} else {
					errStr := fmt.Sprintf("%+v", err)
					errStr = strings.Split(errStr, "\n")[0]
					response.Fail(c, errStr)
					return
				}
			}
		}()
		c.Next()
	}
}

func Authorize(c *gin.Context) {
	auth := c.GetHeader("authorization")
	user := dto.UserInfo{}
	err := redis_util.GetStructWithError(auth, &user)
	if err != nil && errors.Is(err, redis.Nil) {
		c.JSON(403, "未登录，请登录")
		c.Abort()
		return
	}
	c.Set("user", user)
	redis_util.ExpireKey(auth, 24*time.Hour)
}
